#!/bin/bash

# Version: 1.2 (2013-03-09)

if [ "$1" == "" ] || [ "$2" == "" ] ; then
  echo "This stuff replaces in files and filenames"
  echo "Usage: <find_str> <replace_str>"
  exit 1
fi

echo src = $1
echo dest = $2

function cor
{
  echo "$*" | sed "s/\//\\\\\//g"
}

a=`cor $1`
b=`cor $2`

echo src=$a
echo dest=$b

tmp=tmp.tmp
rm $tmp
echo "--------------> Replace in files"
for f in `find -type f` ; do
  echo "process $f"
  if [ "$f" == "./$sol" ] || [ "$f" == "./my_rename.sh" ] ; then
    echo "  skip it"
    continue
  fi
  sed "s/$a/$b/g" $f > $tmp || exit 1
  mv $tmp $f || exit 1
done

echo "--------------> Replace in filenames"
find > $tmp
for f in `tac $tmp` ; do
  echo "process $f"
  if [ "$f" == "./$sol" ] || [ "$f" == "./my_rename.sh" ] ; then
    echo "  skip it"
    continue
  fi
  d=`echo $f | sed "s/[^\/]*$//"`
  n=${f:${#d}:${#f}}
  s=`echo $n | sed "s/$a/$b/g"`
  if [ "$n" != "$s" ] ; then
    echo "in $d rename '$n' --> '$s'"
    mv $d$n $d$s || exit 1
  fi
done
rm $tmp
